package com.zhsecurity.handler;

import com.zhsecurity.AuthenticationResponse;
import com.zhtools.json.JsonWrapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationFailureReturnJsonHandler implements AuthenticationFailureHandler {
    private static final String CHARACTERENCODING = "UTF-8";

    public void onAuthenticationFailure(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding(CHARACTERENCODING);

        AuthenticationResponse authenticationResponse = new AuthenticationResponse();
        authenticationResponse.setMsg(exception.getMessage());

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JsonWrapper.writeValue(authenticationResponse));
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }
}
